package cn.com.leon.controller;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import cn.com.leon.util.Utils;

public class BaseAction<T> implements Action<T>, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3084639646148482736L;
	private List<T> list;
	private String fileName;

	public BaseAction(String fileName){
		this.fileName = fileName;
		this.list = list();
	}
	
	public boolean insert(T entity) {
		if (!isContains(list,entity)) {
			list.add(entity);
			save(list);
			System.out.println("Query OK, 1 row affected, insert success");
			return true;
		}
		System.out.println("Insert fail, it already exist");
		return false;
	}

	public boolean del(T entity) {
		if(!list.isEmpty()){
			for (Iterator<T> iterator = list.iterator(); iterator.hasNext();) {
				T t = iterator.next();
				if(t.equals(entity)){
					list.remove(t);
					save(list);
					System.out.println("Query OK, 1 row affected, delete success");
					return true;
				}
			}
		}else{
			System.out.println("Empty set");
			return false;
		}
		System.out.println("Delete fail, it isnot exist");
		return false;
	}

	public boolean update(T entity) {
		if(!list.isEmpty()){
			for (Iterator<T> iterator = list.iterator(); iterator.hasNext();) {
				T t = iterator.next();
				if(t.equals(entity)){
					list.set(list.indexOf(t), entity);
					save(list);
					System.out.println("Query OK, 1 row affected, update success");
					return true;
				}
			}
		}else{
			System.out.println("Empty set");
			return false;
		}
		System.out.println("Update fail, it isnot exist");
		return false;
	}
	
	public List<T> list() {
		Object ob = Utils.readObjectFromFile(fileName);
		if (ob instanceof List) {
			return (List) ob;
		}
		return null;
	}
	
	public boolean save(List<T> list) {
		Utils.writeObjectIntoFile(fileName, list);
		return true;
	}

	public boolean isContains(List<T> list, T entity) {
		if(!list.isEmpty()){
			for (Iterator<T> iterator = list.iterator(); iterator.hasNext();) {
				T t = iterator.next();
				if(t.equals(entity)){
					return true;
				}
			}
		}else{
			System.out.println("Empty set");
			return false;
		}
		return false;
	}
	
	
}
